﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Xml;
using System.Xml.Serialization;

namespace Pub.Common
{
    public class XmlHelper
    {
        /// <summary>
        /// Xml=>Model
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="xmlStr"></param>
        /// <returns></returns>
        public static T DeSerializeXmlToObject<T>(string xmlStr)
        {
            TextReader textReader = new StringReader(xmlStr);
            XmlSerializer xmlSerializer = new XmlSerializer(typeof(T), string.Empty);
            return (T)xmlSerializer.Deserialize(textReader);
        }

        /// <summary>
        /// Xml=>Model
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="xmlFilePath"></param>
        /// <returns></returns>
        public static T DeSerializeXmlPathToObject<T>(string xmlFilePath)
        {
            string xmlStr = Lib.Utils.FileHelper.ReadPageModel(xmlFilePath, Encoding.UTF8);
            return DeSerializeXmlToObject<T>(xmlStr);
        }

        /// <summary>
        ///  Model=>Xml
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static string SerializeObjectToXml(object obj)
        {
            string xmlStr = string.Empty;
            using (MemoryStream memoryStream = new MemoryStream())
            {
                XmlWriterSettings writerSet = new XmlWriterSettings()
                {
                    CloseOutput = false,
                    Encoding = System.Text.Encoding.UTF8,
                    Indent = false
                };
                XmlWriter writer = XmlWriter.Create(memoryStream, writerSet);
                XmlSerializer xmlSerializer = new XmlSerializer(obj.GetType());
                xmlSerializer.Serialize(writer, obj);
                writer.Close();

                memoryStream.Position = 0;
                StreamReader reader = new StreamReader(memoryStream);
                xmlStr = reader.ReadToEnd();
                memoryStream.Close();
            }
            return xmlStr;
        }
    }
}
